let connStatus = false;
const onMsgs = [];

function init(wsUrl, onMsg = () => {}) {
	if (connStatus) {
		return;
	}
	uni.connectSocket({
		url,
		success() {
			// console.log('WebSocket 连接成功！');
		},
		fail(e) {
			console.log('WebSocket 连接失败！', e);
		},
		complete() {
			// console.log('WebSocket 连接结束！');
		}
	});
	uni.onSocketOpen(function (res) {
		connStatus = true;
		// console.log('WebSocket 连接已打开！');
	});
	uni.onSocketError(function (res) {
		connStatus = false;
		console.log('WebSocket连接打开失败，请检查！');
	});
	uni.onSocketClose(function (res) {
		connStatus = false;
		console.log('WebSocket 已关闭！');
	});
	uni.onSocketMessage(function (res) {
		console.log('收到服务器内容：' + res.data);
		onMsg(res);
		onMsgs.forEach(item => item(res));
	});
}

class NWebsocket {
	constructor(wsUrl, onMsg = () => {}) {
		this.wsUrl = wsUrl;
		this.onMsg = onMsg;
		
		init(this.wsUrl, this.onMsg);
	}
	
	send(data) {
		uni.sendSocketMessage({ data });
	}
	
	addOnMsg: onMsg => onMsgs.push(onMsg);

	close: uni.closeSocket;
}

export default NWebsocket;